package main

import (
	"demogo/global"
	"demogo/initialize"
	"demogo/model"
	"io"
	"log"
	"math/rand"
	"net/http"
	"strconv"
	"strings"

	"time"
)

func main() {
	//if len(os.Getenv("SERVICE_NAME")) > 0 {
	//	serviceName = os.Getenv("SERVICE_NAME")
	//}
	global.ASW_DB = initialize.GormMysql()
	initialize.MysqlTables(global.ASW_DB) // 初始化表
	RunServer()
}

func RunServer() {
	mux := http.NewServeMux()
	mux.HandleFunc("/", IndexServer)
	mux.HandleFunc("/demo/hello", HelloServer)
	mux.HandleFunc("/demo/user", UserServer)
	mux.HandleFunc("/demo/random-error", RandomErrorServer)
	log.Fatal("ListenAndServe: ", http.ListenAndServe(":8080", mux))
}

func IndexServer(w http.ResponseWriter, req *http.Request) {
	log.Printf("%s request to %s\n", req.Method, req.RequestURI)
	base := "[v0.4] curl http://IP:PORT/"
	msg :=  base + "\n" +
		    base + "demo/hello  //hello页面" + "\n" +
		    base + "demo/user  //获取所有用户" + "\n" +
		    base + "demo/user?name=xxx -X PUT  //添加用户" + "\n" +
	        base + "demo/random-error  //获取随机数"
	if _,err := io.WriteString(w, msg); err != nil {
		log.Printf(err.Error())
	}
}

func HelloServer(w http.ResponseWriter, req *http.Request) {
	log.Printf("%s request to %s\n", req.Method, req.RequestURI)
	delay := req.URL.Query().Get("delay")
	if len(delay) > 0 {
		delayNum, _ := strconv.Atoi(delay)
		time.Sleep(time.Duration(delayNum) * time.Second)
	}
	if _,err := io.WriteString(w, "hello, world!\n"); err != nil {
		log.Printf(err.Error())
	}
}

func UserServer(w http.ResponseWriter, req *http.Request) {
	code := http.StatusOK
	msg := "Everything is OK"
	log.Printf("%s request to %s\n", req.Method, req.RequestURI)

	if req.Method == "PUT" {
		name := req.URL.Query().Get("name")
		var user = []model.User{{Name: name, Birthday: time.Now()}}
		if err := global.ASW_DB.Create(&user).Error; err != nil {
			code = http.StatusInternalServerError
			msg = err.Error()
		}
	} else {
		var users []model.User
		if err := global.ASW_DB.Find(&users).Error; err != nil {
			panic(err)
		}
		var names []string
		for _, u := range users {
			names = append(names, u.Name)
		}
		msg = strings.Join(names, "\n")
	}
	w.WriteHeader(code)
	if _,err := io.WriteString(w, msg); err != nil {
		log.Printf(err.Error())
	}
}

func RandomErrorServer(w http.ResponseWriter, req *http.Request) {
	log.Printf("%s request to %s\n", req.Method, req.RequestURI)
	code := http.StatusOK
	rand.Seed(time.Now().UnixNano())
	n := rand.Intn(10)
	msg := "Everything is still OK\n" + strconv.Itoa(n)
	if n == 0 {
		code = http.StatusInternalServerError
		msg = "ERROR: Something, somewhere, went wrong!\n" + strconv.Itoa(n)
		log.Printf(msg)
	}
	w.WriteHeader(code)
	if _,err := io.WriteString(w, msg); err != nil {
		log.Printf(err.Error())
	}
}
